/*
 * Copyright 2016 Wealth Inc. All rights reserved.
 */
 package com.wealth.coupon.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.Interval;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.druid.util.DaemonThreadFactory;
import com.wealth.coupon.entity.Coupon;
import com.wealth.coupon.entity.CouponRecord;
import com.wealth.coupon.entity.CouponRule;
import com.wealth.coupon.enums.CouponRecordStatusEnum;
import com.wealth.coupon.repository.CouponDao;
import com.wealth.coupon.repository.CouponRecordDao;
import com.wealth.coupon.service.ICouponRecordService;
import com.wealth.coupon.util.LabelFileEncrypt;
import com.wealth.member.entity.Member;

import iaas.enums.YesOrNoEnum;
import iaas.service.impl.BaseServiceImpl;
import iaas.utils.ResultObject;

/**
 * @author chan
 */
@Component
public class CouponRecordServiceImpl extends BaseServiceImpl<CouponRecord> implements ICouponRecordService{

	@Autowired
	private CouponRecordDao couponRecordDao;
	@Autowired
	private CouponDao couponDao;

	/**
	 * 验证优惠券是否有效, 针对“纸质优惠券”
	 * create  by chan on 2016-07-24
	 * modify by chan on 2016-09-11 通过唯一标识查询优惠券，判断序列号范围
	 */
	@Override
	public ResultObject isValid(Long memberid,String code) throws Exception{
		if(StringUtils.isBlank(code)){
			return new ResultObject("500", "优惠券序列号不能为空", "");
		}

		//唯一标识
		String uid = code.substring(0, 4);
		Coupon batch =couponDao.findByUid(uid);
		if(batch==null){
			return new ResultObject("500", "优惠券序列号非法", "");
		}

		//序列号
		int sn = Integer.parseInt(LabelFileEncrypt.decrypt(code)); 
		boolean flag = (sn>=batch.getStartno() && sn <=batch.getEndno());
		if(!flag){
			return new ResultObject("500", "优惠券序列号非法", "");
		}
		
		//间隔
		DateTime start = new DateTime(batch.getRule().getStartTime());
		DateTime end = new DateTime(batch.getRule().getEndTime());
		Interval i = new Interval(start, end);
		if(!i.contains(new DateTime())){
			return new ResultObject("500", "优惠券已过期", "");
		}
		
		return new ResultObject("200", "优惠券有效",batch.getRule());
	}

	
	/**
	 * 添加优惠券, 针对“纸质优惠券”
	 */
	@Override
	public ResultObject saveCoupon(Long memberid, String code) throws Exception {
		//验证优惠券是否有效
		ResultObject rs  = isValid(memberid,code);
		if(rs.getCode()=="500"){
			return rs;
		}
		//是否添加过
		List<CouponRecord> voucherRecordList = couponRecordDao.findByMemberIdAndCode(memberid, code);
		if(voucherRecordList.size()>0){
			return new ResultObject("500", "该优惠券已添加", "");
		}
		
		//添加
		CouponRule rule = (CouponRule) rs.getResult();
		CouponRecord record = new CouponRecord();
		record.setCode(code);
		record.setCreateTime(new Date());
		record.setMember(new Member(memberid));
		record.setRule(rule);
		record.setStatus(CouponRecordStatusEnum.UNUSED.getValue());//未使用
		couponRecordDao.save(record);
		return new ResultObject("200", "添加优惠券成功", record);
	}
	
	
	
	/**
	 * 使用优惠券
	 */
	@Override
	public ResultObject useCoupon(Long orderid,Long couponRecordId) throws Exception{
		CouponRecord record = couponRecordDao.findOne(couponRecordId) ;
		//是否使用过
		if(record.getStatus()==CouponRecordStatusEnum.USED.getValue()){
			return new ResultObject("500", "优惠券已被使用", "");
		}
		//是否过期
		DateTime start = new DateTime(record.getRule().getStartTime());
		DateTime end = new DateTime(record.getRule().getEndTime());
		Interval i = new Interval(start, end);
		if(!i.contains(new DateTime())){
			return new ResultObject("500", "优惠券已过期", "");
		}
		record.setStatus(CouponRecordStatusEnum.USED.getValue());//使用
		couponRecordDao.save(record);
		return new ResultObject("200", "使用优惠券成功", "");
	}


	/**
	 * 生成优惠券，针对“系统发放优惠券”
	 * 
	 * 目前支持：优惠券批次模式为完善地址 CouponModeEnum.COMPLETEADDRESS=2
	 */
	public ResultObject generateCoupon(Long memberid,Long corpid,Integer couponMode) throws Exception{
		Coupon coupon =  couponDao.findByMode(couponMode);
		//已发送的优惠券数量
		int qty = couponRecordDao.calcCouponRecordByCouponMode(couponMode, corpid);
		if(coupon.getQuantity()<qty){
			return new ResultObject("500", "优惠券全部发光了", "");
		}
		
		String uid = coupon.getUid();
		String code  = LabelFileEncrypt.encrypt(uid);
		CouponRecord record = new CouponRecord();
		record.setMember(new Member(memberid));
		record.setCode(code);
		record.setStatus(YesOrNoEnum.NO.getValue());	//未使用
		record.setCreateTime(new Date());
		record.setRule(coupon.getRule());
		couponRecordDao.save(record);
		return new ResultObject("000", "领取优惠券成功", "");
		
	}
	
	
	
	
	
	
	/**
	 * 查询优惠券 
	 */
	public List<CouponRecord> getCouponRecordByMemberIdAndStatus(Long memberid,Integer status)throws Exception{
		if(status!=null){
			return couponRecordDao.findByMemberIdAndStatus(memberid, status);
		}
		return couponRecordDao.findByMemberId(memberid);
	}
		
	/**
	 * 会员可用优惠券
	 * 会员+大于最小消费金额+大于面值+活动期间+状态
	 * create by chan on 2016-07-25 
	 */
	@Override
	public List<CouponRecord> getUsableCouponRecord(Long memberid, Double total) throws Exception {
		return couponRecordDao.findByMemberIdAndRuleMinAmountLessThanEqualAndRuleUsageAmountLessThanEqualAndStatusAndRuleStartTimeLessThanEqualAndRuleEndTimeGreaterThanEqual(
				memberid, total, total, CouponRecordStatusEnum.UNUSED.getValue(), new Date(), new Date());
	}


	@Override
	public ResultObject receiveCoupon(Long memberid, Long corpid)
			throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}
